import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:photo_kit/debug_tool.dart';
import 'package:photo_kit/photo_kit.dart';

import 'photo_asset.dart';

class PohtoTextureValue {}

class PhotoTextureController extends ValueNotifier<PohtoTextureValue> {
  final PhotoAsset asset;

  PhotoTextureController(this.asset) : super(null);

  int _textureId;
  int get textureId => _textureId;

  Completer<void> _creatingCompleter;
  bool _isDisposed = false;

  Future<void> initialize() async {
    _creatingCompleter = Completer<void>();

    // 生成了就不再创建
    if (_textureId == null || _textureId < 0) {
      _textureId = await PhotoKit.createTexture(asset.identity);
      if (_textureId is int) this.value = PohtoTextureValue();
      dprint('生成纹理 id: $_textureId');
    }

    _creatingCompleter.complete(null);
  }

  Future<bool> update({int width = -1, int height = -1}) async {
    final result = await PhotoKit.updateTexture(
      asset.identity,
      width: width,
      height: height,
    );
    // 内部已经刷新了纹理
    // if (result) this.value = PohtoTextureValue();

    return result;
  }

  Future<void> disposeTexture() async {
    if (_creatingCompleter != null) {
      await _creatingCompleter.future;
      if (!_isDisposed) {
        await PhotoKit.disposeTexture(asset.identity);
        _textureId = null;
      }
    }
  }

  @override
  Future<void> dispose() async {
    if (!_isDisposed) {
      await disposeTexture();
      _isDisposed = true;
    }

    _isDisposed = true;
    super.dispose();
  }
}
